import 'package:flutter_cwhisky/bean/classify_entity.dart';
import 'package:flutter_cwhisky/component/base/base_controller.dart';
import 'package:get/get.dart';

import '../../../bean/good_entity.dart';
import '../../../bean/good_list_entity.dart';
import '../../../common/constant/api.dart';
import '../../../net/http_service.dart';

class ClassifyLogic extends BaseController {
  List<ClassifyData> classifyList = [];
  ClassifyData? currentClassify;

  int currentIndex = 1;
  List<GoodEntity>? goodList;

  @override
  void onInit() {
    super.onInit();
    _fetchClassify();
  }

  void _fetchClassify() async {
    var response = await api.request(Api.classifyList, method: HttpService.methodGet);
    if (response.isSuccess) {
      classifyList.clear();
      var all = ClassifyData();
      all.name = '全部';
      classifyList.add(all);
      var list = ClassifyEntity.fromJson(response.data).data!;
      classifyList.addAll(list);
      currentClassify = list[0];
      update(['classifyList']);
      _fetchGood();
    }
  }

  onClickClassify(int index) {
    if(currentIndex != index){
      currentIndex = index;
      currentClassify = classifyList[index];
      update(['classifyList']);
      _fetchGood();
    }

  }

  void _fetchGood() async {
    var response = await api.request(Api.goodList,
        method: HttpService.methodPost,
        params: {"from": 1, "size": 20, "current": 1, "classifyCode": currentClassify!.code});
    if (response.isSuccess) {
      goodList = GoodListEntity.fromJson(response.data).data!.records;
      print('怎么回事呢=${goodList}');
      update(['GoodList']);
    }
  }
}
